<template>
  <div class="cart">
    <div class="container">
      <h2>购物车</h2>
      <div v-if="cartItems.length === 0" class="empty-cart">
        <p>购物车为空</p>
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </div>
      <div v-else class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <img :src="item.image" :alt="item.name" />
          <div class="item-info">
            <h3>{{ item.name }}</h3>
            <p class="price">¥{{ item.price }}</p>
          </div>
          <div class="quantity-control">
            <el-button @click="decreaseQuantity(item)">-</el-button>
            <span>{{ item.quantity }}</span>
            <el-button @click="increaseQuantity(item)">+</el-button>
          </div>
          <el-button type="danger" @click="removeItem(item)">删除</el-button>
        </div>
        <div class="cart-total">
          <p>总计: ¥{{ totalPrice }}</p>
          <el-button type="primary" size="large">去结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

interface CartItem {
  id: number
  name: string
  price: number
  image: string
  quantity: number
}

const cartItems = ref<CartItem[]>([
  { id: 1, name: 'iPhone 15 Pro', price: 7999, image: '/images/iphone15.jpg', quantity: 1 },
  { id: 2, name: 'MacBook Pro', price: 12999, image: '/images/macbook.jpg', quantity: 1 }
])

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

const increaseQuantity = (item: CartItem) => {
  item.quantity++
}

const decreaseQuantity = (item: CartItem) => {
  if (item.quantity > 1) {
    item.quantity--
  }
}

const removeItem = (item: CartItem) => {
  cartItems.value = cartItems.value.filter(i => i.id !== item.id)
}
</script>

<style scoped>
.cart {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 2rem 0;
}

.empty-cart {
  text-align: center;
  padding: 4rem;
}

.cart-item {
  display: flex;
  align-items: center;
  background: white;
  padding: 1rem;
  margin-bottom: 1rem;
  border-radius: 8px;
}

.cart-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 1rem;
}

.item-info {
  flex: 1;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0 2rem;
}

.cart-total {
  text-align: right;
  margin-top: 2rem;
  padding: 1rem;
  background: white;
  border-radius: 8px;
}
</style>